import {ActionPanel, Detail, LaunchProps,Action, List, showToast, Toast, useNavigation} from "@raycast/api";
import {match} from "assert";
import {useEffect, useState} from "react";
import {request} from "./api";

const ChatWindow =  (props:{prompt:string}) => {
    const [chatRes, setChatRes] = useState<string>()
    const [code,setCode] = useState<string>()
    useEffect(() => {
        request({
            model: "chatglm_lite"
            , req: {
                prompt: [
                    {role: "user", content: props.prompt},
                ]
            }
        }).then(r => {
            if (r.data.code == 200) {
                let content = r.data.data.choices[0].content
                content = content.replaceAll("\\n", " \n ")
                content = content.replaceAll("\\\"", "\"")
                setChatRes(content)
                console.log("content",content)
                const code_ = content.match("(?<=```.*\\n)([\\s\\S]*?)(?=```)")
                console.log("code_",code_)
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                setCode(code_.join("\n"))

            } else {
                showToast({
                    style: Toast.Style.Success,
                    title: "处理失败",
                    message: r.data.msg,
                }).then();
            }
        })
    }, [])
    return  <Detail navigationTitle={props.prompt} markdown={chatRes ?? "# 正在处理..."} actions={
        <ActionPanel title="#1 in raycast/extensions">
            <Action.CopyToClipboard  title="复制代码部分" content={code!}  />
        </ActionPanel>
    }/>

}

const languageList = [
    "Golang",
    "JavaScript",
    "Java",
    "Python",
    "Rust",
]

export default function Command(props: LaunchProps<{ arguments: { prompt: string } }>) {
    const {push} = useNavigation();
    return (
        <List navigationTitle="Open Pull Requests">
            {languageList.map((item,index) => {
                return <List.Item
                    key={index}
                    title={`生成: ${item} 代码`}
                    subtitle={`#${index+1}`}
                    actions={
                        <ActionPanel title="#1 in raycast/extensions">
                            <Action title="生成" onAction={() => push(<ChatWindow prompt={`生成: ${item} 代码: ${props.arguments.prompt}`}/>)} />
                        </ActionPanel>
                    }
                />
            })}
        </List>
    );
}
